const getScrollTop = () => {
  return (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
}

const setScrollTop = (value, element) => {
  if (element) {
    element.scrollTo(0, value);
  } else {
    window.scrollTo(0, value);
  }
  return value;
}

const requestAnimFrame = (function () {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function (callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

const scrollTo = (to, duration, el) => {
  if (duration < 0) {
      setScrollTop(to, el);
      return
  }
  var diff = to - getScrollTop();
  if (diff === 0) return
  var step = diff / duration * 10;
  requestAnimationFrame(
    function () {
      if (Math.abs(step) > Math.abs(diff)) {
        setScrollTop(getScrollTop() + diff, el);
        return;
      }
      setScrollTop(getScrollTop() + step, el);
      if (diff > 0 && getScrollTop() >= to || diff < 0 && getScrollTop() <= to) {
        return;
      }
      scrollTo(to, duration - 16, el);
    });
}

export { scrollTo, getScrollTop, setScrollTop }